<template>
  <div class="json-editor">
    <textarea ref="textarea"></textarea>
  </div>
</template>

<script>
import CodeMirror from 'codemirror'
import 'codemirror/addon/lint/lint.css'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/rubyblue.css'
import 'codemirror/theme/erlang-dark.css'
require('script-loader!jsonlint')
import 'codemirror/mode/javascript/javascript'
import 'codemirror/addon/lint/lint'
import 'codemirror/addon/lint/json-lint'
import 'codemirror/addon/display/autorefresh'

export default {
  name: 'jsonEditor',
  data() {
    return {
      jsonEditor: false
    }
  },
  props: {
    value: {
      String,
      default: ''
    }
  },
  watch: {
    value(value) {
      const editor_value = this.jsonEditor.getValue()
      if (value !== editor_value) {
        this.setValue(this.value)
      }
    }
  },
  mounted() {
    this.jsonEditor = CodeMirror.fromTextArea(this.$refs.textarea, {
      lineNumbers: true,
      lineWrapping: false, // 在长行时文字是换行(wrap)还是滚动(scroll)，默认为滚动(scroll)
      mode: 'application/json',
      gutters: ['CodeMirror-lint-markers'],
      theme: 'rubyblue',
      lint: true,
      autoRefresh: true
    })

    this.setValue(this.value)
    this.jsonEditor.on('blur', codemirror => {
      try {
        JSON.parse(codemirror.getValue())
        this.$emit('blur', codemirror.getValue())
      } catch (error) {
        this.$message.error('JSON格式不正确')
      }
    })
    this.jsonEditor.on('change', codemirror => {
      try {
        JSON.parse(codemirror.getValue())
        this.$emit('change', codemirror.getValue())
      } catch (error) {
        this.$message.error('JSON格式不正确')
      }
    })
  },
  methods: {
    getValue() {
      try {
        JSON.parse(this.jsonEditor.getValue())
        return this.jsonEditor.getValue()
      } catch (error) {
        console.error('getValue  JSON格式不正确')
        this.$message.error('JSON格式不正确')
      }
    },
    setValue(value) {
      try {
        if (typeof value === 'string') {
          if (value === '') {
            this.jsonEditor.setValue(value, null, 2)
          } else {
            this.jsonEditor.setValue(JSON.stringify(JSON.parse(value), null, 2))
          }
        } else {
          this.jsonEditor.setValue(JSON.stringify(this.value, null, 2))
        }
      } catch (error) {
        console.error('setValue  JSON格式不正确')
        this.$message.error('JSON格式不正确')
      }
    }
  }
}
</script>

<style scoped>
.json-editor {
  height: 100%;
}
.json-editor>>>.CodeMirror {
  height: auto;
  min-height: 300px;
}
.json-editor>>>.CodeMirror-scroll {
  min-height: 300px;
}
.json-editor>>>.cm-s-rubyblue span.cm-string {
  color: #f08047;
}
.CodeMirror {
  border: 1px solid #eee;
  height: auto;
}

.CodeMirror-scroll {
  height: auto;
  overflow-y: hidden;
  overflow-x: auto;
}
.CodeMirror {
  border: 1px solid #eee;
  height: auto;
}

.CodeMirror-scroll {
  height: auto;
  overflow-y: hidden;
  overflow-x: auto;
}
</style>
